package com.demon.mutehelper

import android.Manifest
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.activity.result.contract.ActivityResultContracts
import androidx.activity.viewModels
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.demon.mutehelper.awareness.LocationAndTimeClient
import com.demon.mutehelper.bean.MuteRecord
import com.demon.mutehelper.databinding.ActivityMainBinding
import com.demon.mutehelper.databinding.ActivityMainListItemBinding
import com.demon.mutehelper.viewmodel.MainViewModel
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch

class MainActivity : AppCompatActivity() {

  private val mViewModel: MainViewModel by viewModels()
  private lateinit var mBinding: ActivityMainBinding
  private var mRecordId: Int? = null
  private lateinit var mLocationAndTimeClient: LocationAndTimeClient
  private val mAdapter =
    MainListItemAdapter(ClickHandler(), object : DiffUtil.ItemCallback<MuteRecord>() {
      override fun areItemsTheSame(oldItem: MuteRecord, newItem: MuteRecord): Boolean {
        return oldItem == newItem
      }

      override fun areContentsTheSame(oldItem: MuteRecord, newItem: MuteRecord): Boolean {
        return oldItem.id == newItem.id
      }

    })

  private val permissionsRequestLauncher =
    registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) {
      startActivity(MuteRecordEditActivity.makeIntent(this@MainActivity, mRecordId))
    }

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    mBinding = DataBindingUtil.setContentView(this, R.layout.activity_main)
    mLocationAndTimeClient = LocationAndTimeClient(this)
    initView()
    initToolbar()
    subscribeUI()
  }

  private fun initView() {
    mBinding.listView.adapter = mAdapter
  }

  private fun subscribeUI() {
    lifecycleScope.launch {
      mViewModel.getRecordList().collect {
        Log.d("YZZ", "on list chancged")
        mAdapter.submitList(it)
        addBarrier(it)
      }
    }
  }

  private fun addBarrier(records: List<MuteRecord>) {
    // 先删除全部
    mLocationAndTimeClient.deleteBarriers()
    records.forEach {
      mLocationAndTimeClient.add(it)
    }
  }

  private fun initToolbar() {
    mBinding.toolBar.apply {
      inflateMenu(R.menu.toolbar_menu)
      setOnMenuItemClickListener {
        when (it.itemId) {
          R.id.action_add -> {
            mRecordId = null
            permissionsRequestLauncher.launch(
              arrayOf(
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION,
              )
            )
          }
        }
        true
      }

    }
  }

  override fun onSaveInstanceState(outState: Bundle) {
    super.onSaveInstanceState(outState)

  }

  inner class ClickHandler {
    fun onItemClicked(muteRecord: MuteRecord) {
      mRecordId = muteRecord.id
      permissionsRequestLauncher.launch(
        arrayOf(
          Manifest.permission.ACCESS_FINE_LOCATION,
          Manifest.permission.ACCESS_COARSE_LOCATION,
        )
      )
    }
  }

  class MainListItemViewHolder(private val binding: ActivityMainListItemBinding) :
    RecyclerView.ViewHolder(binding.root) {
    fun bind(item: MuteRecord, clickHandler: ClickHandler) {
      binding.item = item
      binding.clickHandler = clickHandler
    }
  }

  class MainListItemAdapter(
    private val clickHandler: ClickHandler,
    diffCallback: DiffUtil.ItemCallback<MuteRecord>
  ) : ListAdapter<MuteRecord, MainListItemViewHolder>(diffCallback) {
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MainListItemViewHolder {
      val binding =
        ActivityMainListItemBinding.inflate(LayoutInflater.from(parent.context), parent, false)
      return MainListItemViewHolder(binding)
    }

    override fun onBindViewHolder(holder: MainListItemViewHolder, position: Int) {
      holder.bind(getItem(holder.adapterPosition), clickHandler)
    }

  }

}